import { reactive, ref } from "vue";
export default function(form) {
	const formData = reactive({
		mobile: '',
		code: '',
		captcha: ''
	})
	const tips = ref('获取验证码');
	const seconds = 60;

	function checkField(name) {
		return new Promise((resolve, reject) => {
			form.value.validateField('mobile', err => {
				if (err[0]?.message) {
					reject(false);
				} else {
					resolve(true);
				}
			})
		})
	}
	// 获取短信验证码
	async function getCode(scene = 'login-by-sms', code) {
		try {
			await checkField('mobile');
			sending();
			const uniIdCo = uniCloud.importObject("uni-id-co", {
				customUI: true
			})
			uniIdCo.sendSmsCode({
				"mobile": formData.mobile,
				"scene": scene,
				"captcha": formData.captcha
			}).then(result => {
				getApp().globalData.notify({
					message: '短信验证码发送成功'
				})
				code.start();
			}).catch(e => {
				end();
				if (e.code == "uni-id-invalid-sms-template-id") {
					formData.code = "123456"
					console.warn(e.message);
				} else {
					end();
					getApp().globalData.notify({
						type: 'error',
						message: e.message
					})
				}
			})
		} catch (e) {}
	}

	function sending() {
		tips.value = '发送中';
	}
	// 发送验证码后倒计时开始
	function start() {
		tips.value = `${seconds}秒重新获取`;
	}
	// 发送验证码后倒计时结束
	function end() {
		tips.value = '获取验证码';
	}
	// 倒计时
	function codeChange(text) {
		tips.value = text;
	}
	return {
		formData,
		tips,
		seconds,
		getCode,
		start,
		end,
		codeChange
	}
}